import initLoginBg from "./init.ts";
import {ChangeEvent, useEffect, useState} from "react";
// import LoginForm from "@/components/LoginForm";
import styles from "@/pages/Login/login.module.scss";
import {Button, Input, message, Space} from "antd";
import {loginApi} from '@/api/Login.ts';
import {useNavigate} from "react-router-dom";

export default () => {
    // 跳转
    const navigateTo = useNavigate();

    // 加载完这个组件之后，加载背景
    useEffect(()=>{
        initLoginBg();
        window.onresize = function(){initLoginBg()};
    },[]);

    // 定义字段
    const [usernameVal, setUsernameVal] = useState('');
    const [passwordVal, setPassword] = useState('');


    // 处理输入字段变化的函数
    const usernameChange = (event: ChangeEvent<HTMLInputElement>) => {
        setUsernameVal(event.target.value);
        console.log('用户名', event.target.value);
    }
    const passwordChange = (event: ChangeEvent<HTMLInputElement>) => {
        setPassword(event.target.value);
        console.log('密码', event.target.value);
    }

    // 处理登录的函数
    const handleLogin = async () => {
        // 判断必填
        if (!usernameVal.trim() || !passwordVal.trim()) {
            message.warning('请填写用户名和密码');
            return;
        }
        // 在这里添加登录逻辑
        // console.log('New Login with:', this.state);
        await loginApi({
            username: usernameVal,
            password: passwordVal,
        }).then((res) => {
            if (res.code === 400) {
                message.error(res.msg);
            }else{
                // 提示登录成功
                message.success(res.msg);
                // 保存token
                localStorage.setItem('lege-token', res.data.token);
                // 跳转到/index
                navigateTo('/index');
                // 清空临时数据(可选)
            }
            console.log(res);
        });
    }

    return (
        <div className={styles.loginPage}>
            {/* 存放背景 */}
            <canvas id="canvas" style={{display:"block"}}></canvas>
            {/* 登录盒子 */}
            <div className={styles.loginBox+ " loginbox"}>
                {/* 标题部分 */}
                <div className={styles.title}>
                    <h1>前端乐哥&nbsp;·&nbsp;通用后台系统</h1>
                    <p>Strive Everyday</p>
                </div>
                {/* 表单部分 */}
                <div className="form">
                    {/*<LoginForm />*/}
                    <Space direction="vertical" size="large" style={{ display: 'flex' }}>
                        <Input name="username" placeholder="用户名" onChange={usernameChange} />
                        <Input.Password name="password" placeholder="密码" onChange={passwordChange}/>
                        {/* 验证码盒子 */}
                        <Button type="primary" className="loginBtn" onClick={handleLogin} block>登录</Button>
                    </Space>
                </div>
            </div>
        </div>
    )
};